package com.monkeygroup.mygoplus.view.home.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.common.DefinedView.MyDialog;
import com.monkeygroup.mygoplus.ecchat.common.utils.FunUtil;
import com.monkeygroup.mygoplus.ecchat.ui.chatting.GlobalConstant;
import com.monkeygroup.mygoplus.ecchat.ui.contact.AddFriendMainActivity;
import com.monkeygroup.mygoplus.ecchat.ui.contact.adapter.RecommendExpandableListAdapter;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactDTO;
import com.monkeygroup.mygoplus.ecchat.ui.recommend.RecommendListActivity;
import com.monkeygroup.mygoplus.ecchat.ui.recommend.entity.CommonMemberDTO;
import com.monkeygroup.mygoplus.ecchat.ui.recommend.entity.GroupDTO;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.view.home.activity.MainActivity;
import com.yuntongxun.ecsdk.ECMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/25.
 */
public class RecommendFragment extends Fragment implements View.OnClickListener {
    private View mView;
    private ExpandableListView recommendListView;
    private RecommendExpandableListAdapter adapter;
    private MainActivity mParent = null;
    private List<GroupDTO> recommendDataList = new ArrayList<>();
    private Map<String, String> mParams = new HashMap<>();
    private long timeCount;
    private Dialog dialog = null;
    private final String TAG = "RecommendFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_chat_recommend, container, false);
            mParent = (MainActivity) getActivity();
            initView();
            initListener();
            initData();
        }
        return mView;
    }

    private void initView() {
        recommendListView = (ExpandableListView) mView.findViewById(R.id.recommendListView);
    }

    private void initListener() {
        mView.findViewById(R.id.layout_back).setOnClickListener(this);
        mView.findViewById(R.id.add_friend).setOnClickListener(this);
        mView.findViewById(R.id.tab_contact).setOnClickListener(this);
        mView.findViewById(R.id.tab_conversation_list).setOnClickListener(this);
    }

    private void initData() {
        initParams();
        initRecommendData();
        initAdapter();

//        doTimeInfo();
    }

    /**
     * 臨時搭建數據
     **/
    private void initRecommendData() {
        recommendDataList.add(new GroupDTO("經紀人", "2", "1", null));
        recommendDataList.add(new GroupDTO("營業員", "3", "2", null));
        recommendDataList.add(new GroupDTO("專家", "11", "3", null));
    }

    private void initAdapter() {
        adapter = new RecommendExpandableListAdapter(getActivity(), recommendDataList);
        recommendListView.setAdapter(adapter);
        recommendListView.setGroupIndicator(null);
        recommendListView.setVerticalScrollBarEnabled(false);

        recommendListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {

                ImageView icon = (ImageView) v.findViewById(R.id.groupIcon);
                if (icon.getTag().equals(0)) {
                    icon.setImageResource(R.drawable.chat_contact_show);
                    icon.setTag(1);

//                    refreshExpandGroup(groupPosition, true);
                } else if (icon.getTag().equals(1)) {
                    icon.setImageResource(R.drawable.chat_contact_hide);
                    icon.setTag(0);

//                    refreshExpandGroup(groupPosition, false);
                }
                return false;
            }
        });

        recommendListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                CommonMemberDTO commonMemberDTO = adapter.getChild(groupPosition, childPosition);
                CommonMemberDTO.Type type = commonMemberDTO.getType();

                if (type == CommonMemberDTO.Type.NONE) {
                    Intent intent = new Intent(getActivity(), RecommendListActivity.class);
                    intent.putExtra("groupid", adapter.getGroup(groupPosition).getGroupId());
                    startActivity(intent);

                    return false;
                } else {
                    if (!MyGoApplication.getContacts().containsKey(commonMemberDTO.getSeq())) {
                        dialog = new MyDialog(getActivity(), R.style.MyDialogTheme, commonMemberDTO.getSeq(), new MyDialog.OnCommonClickListener() {
                            @Override
                            public void doClick(String var1) {
                                dialog.dismiss();
                                FunUtil.addFriend(var1);
                            }
                        });
                    } else {
                        final String friendid = commonMemberDTO.getSeq();
                        final boolean isFavorite;
                        if (MyGoApplication.getConcernList().containsKey(friendid)) {
                            isFavorite = true;
                        } else {
                            isFavorite = false;
                        }

                        dialog = new MyDialog(getActivity(), R.style.MyDialogTheme, isFavorite, new MyDialog.OnFriendExchangeListener() {
                            @Override
                            public void doMessage() {
                                dialog.dismiss();
                                Intent intent = new Intent(getActivity(), MainActivity.class);
                                intent.setAction(GlobalConstant.ACTION_ENTER_NEW_CHATROOM);
                                intent.putExtra("userid", friendid);
                                startActivity(intent);
                            }

                            @Override
                            public void doCall() {
                                dialog.dismiss();
                                FunUtil.handleVoiceCall(getActivity(), friendid);
                            }

                            @Override
                            public void doVideo() {
                                dialog.dismiss();
                                FunUtil.handleVideoCall(getActivity(), friendid);
                            }

                            @Override
                            public void doFavorite(ImageView view) {
                                if (isFavorite) {
                                    FunUtil.doCancelConcern(friendid, view);
                                } else {
                                    FunUtil.doConcern(friendid, view);
                                }
                            }
                        });
                    }
                    dialog.show();
                }

                return false;
            }
        });
    }

    private void refreshExpandGroup(int position, boolean isExpand) {
        if (isExpand) {
            recommendListView.expandGroup(position);
        } else {
            recommendListView.collapseGroup(position);
        }
    }

    private void showFragment(String tag) {
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        Fragment fragment = fragmentManager.findFragmentByTag(tag);

        mParent.setFragment(fragment);
    }

    private void doTimeInfo() {
        HttpModel httpModel = new HttpModel(RequestUrl.getMygoTime(), new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (data == null)
                    return;

                String jsonData = (String) data;
                String status = "";
                try {
                    JSONObject object = new JSONObject(jsonData);
                    status = object.getString("status");
                    timeCount = object.getInt("timestamp");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (status.equals("ERROR_OK")) {
                    initParams();
                    doRecommendUsers(null);
                } else {
                    Toast.makeText(getActivity(), resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.Request();
    }

    private void doRecommendUsers(final String groupId) {
        mParams.put("specialcg", groupId);
        HttpModel httpModel = new HttpModel(RequestUrl.getSearchUserList(), mParams, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (data == null)
                    return;

                String jsonData = (String) data;
                String status = "", dataList = "";
                try {
                    JSONObject object = new JSONObject(jsonData);
                    status = object.getString("status");
                    dataList = object.getJSONArray("agent").toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (status.equals("ERROR_OK")) {
                    Gson gson = new Gson();
                    List<CommonMemberDTO> list = gson.fromJson(dataList, new TypeToken<List<CommonMemberDTO>>() {
                    }.getType());

                    if (list != null && list.size() > 0) {
                        rebuildRecommendData(groupId, list);
                    }

                } else {
                    Toast.makeText(getActivity(), resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.Request();
    }

    private void initParams() {
//        mParams.put("t", String.valueOf(timeCount));
//        mParams.put("m", md5(RequestUrl.getSearchUserList() + String.valueOf(timeCount)));
        mParams.put("searchKey", "");
        mParams.put("lat", "");
        mParams.put("lng", "");
        mParams.put("scope", "");
        mParams.put("region", "");
        mParams.put("state", "");
        mParams.put("city", "");
        mParams.put("area", "");
        mParams.put("specialcg", "2");
        mParams.put("typeitem", "");
        mParams.put("star", "");
        mParams.put("pagesize", "5");
        mParams.put("page", "1");
        mParams.put("order", "default");
    }

    private void rebuildRecommendData(String groupId, List<CommonMemberDTO> list) {
        List<CommonMemberDTO> memberList = new ArrayList<>();
        for (CommonMemberDTO memberDTO : list) {
            memberDTO.setType(CommonMemberDTO.Type.RECOMMEND);
            memberList.add(memberDTO);
        }

        CommonMemberDTO member = new CommonMemberDTO();
        if (groupId.equals("2")) {
            member.setName("查看更多經紀人");
        } else if (groupId.equals("3")) {
            member.setName("查看更多營業員");
        } else {
            member.setName("查看更多專家");
        }

        member.setType(CommonMemberDTO.Type.NONE);
        memberList.add(member);

        for (GroupDTO group : recommendDataList) {
            if (group.getGroupId().equals(groupId)) {
                group.setMemberList(memberList);
                break;
            }
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * MD5加密
     **/
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }

        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }

            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (recommendDataList.get(0).getMemberList() == null) {
                for (GroupDTO groupDTO : recommendDataList) {
                    doRecommendUsers(groupDTO.getGroupId());
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.layout_back:
            case R.id.tab_conversation_list:
                mParent.setChatFocusIndex(0);
                showFragment("mConversationFragment");
                break;
            case R.id.tab_contact:
                mParent.setChatFocusIndex(1);
                showFragment("mContactFragment");
                break;
            case R.id.add_friend:
                intent.setClass(getActivity(), AddFriendMainActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }
}
